package com.hfzy.ihk.web.freeswitchManage.support.swx;

import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.freeswitchManage.enums.SwxTrunkStatusEnum;
import com.hfzy.ihk.web.freeswitchManage.constant.RedisFields;
import com.hfzy.ihk.web.freeswitchManage.constant.RedisKeys;
import com.hfzy.ihk.web.freeswitchManage.mapper.GatewayCardSlotMapper;
import com.hfzy.ihk.web.freeswitchManage.support.base.AbstractEquipmentControlProcess;
import com.hfzy.ihk.web.freeswitchManage.vo.GatewayCardSlotVo;
import com.hfzy.ihk.web.freeswitchManage.vo.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YANFA on 2019/4/8.
 */
@Component
@Slf4j
public class SwxEquipmentControlProcess extends AbstractEquipmentControlProcess {

    @Autowired
    private RedisTemplate redisTemplate;



    @Autowired
    private GatewayCardSlotMapper gatewayCardSlotMapper;

    /**
     * 将空闲状态入队
     */
    @Override
    public void putIdleChannelQueue(RedisData redisData) {
        //通过通道名获得当前通道的所属城市，并且生成
        String status = redisData.getStatus();
        if(status==null){
            log.info(">>set redis queque status is null!");
            return;
        }
        log.info(">>set redis queque status:{}",status);
        if(SwxTrunkStatusEnum.IDLE.getValue().equals(status)){//空闲，入队

            Object channelStatus = redisTemplate.opsForHash().get(redisData.getChannelMapName(), redisData.getSn()+":"+redisData.getTrunkName());
            log.info("channelStatus:{}",channelStatus);
            if (channelStatus == null || !SwxTrunkStatusEnum.IDLE.getValue().equals(channelStatus.toString())) { //缺失的，就放入队列和写入map

                redisTemplate.opsForList().rightPush(redisData.getQueueName(),redisData.getSn()+":"+redisData.getTrunkName());
            }
        log.info(">>set redis queque success!");
        }


    }

    /**
     * 生成一个附属Map用于监控空闲状态是否有遗漏的情况 key :company:city:swxChannelMap -trunkName
     */
    @Override
    public void putIdleChannelMap(RedisData redisData) {

        String status = redisData.getStatus();
        if(status==null){
            log.info(">>set redis channelMap status is null!");
            return;
        }

        log.info(">>set redis channelMap status:{}",status);

        if(SwxTrunkStatusEnum.IDLE.getValue().equals(status)){//空闲，入队
            redisTemplate.opsForHash().put(redisData.getChannelMapName(),redisData.getSn()+":"+redisData.getTrunkName(),status);
            log.info(">>set redis channelMap success!");
        }

    }

    /**
     * 更新redis里面的每个卡槽的状态
     * map --这个map记录了卡槽的所有信息，包括sip user 公司等信息
     */
    @Override
    public void updateChannelSlotState(RedisData redisData) {
        redisTemplate.opsForHash().put(RedisKeys.slotInfoKey(redisData.getSn(),redisData.getTrunkName()), RedisFields.STATE,redisData.getStatus());
        log.info(">>set Channel Slot State success!");
    }



    /**
     * 判断队列是否有丢失的idle 如果有就补回，----job补偿
     */
    @Override
    public  void checkQueueIdle(RedisData redisData){
        try {
            if (SwxTrunkStatusEnum.IDLE.getValue().equals(redisData.getStatus())) {
                String companyAndCity = getRedisQueueCompanyAndCity(redisData);

                Object status = redisTemplate.opsForHash().get(companyAndCity + RedisKeys.SWX_CHANNEL_MAP, redisData.getSn()+":"+redisData.getTrunkName());
                log.info(">>check redis QueueIdle status:{}",status);

                if (status == null || !SwxTrunkStatusEnum.IDLE.getValue().equals(status.toString())) { //缺失的，就放入队列和写入map

                    redisTemplate.opsForList().rightPush(companyAndCity + RedisKeys.SWX_CHANNEL_QUEUE, redisData.getSn()+":"+redisData.getTrunkName());

                    redisTemplate.opsForHash().put(companyAndCity + RedisKeys.SWX_CHANNEL_MAP, redisData.getSn()+":"+redisData.getTrunkName(), redisData.getStatus());
                    log.info(">>check redis QueueIdle success!");


                }
                // 更新通道信息map
                redisTemplate.opsForHash().put(RedisKeys.slotInfoKey(redisData.getSn(),redisData.getTrunkName()),RedisFields.STATE,redisData.getStatus());

            }
        }catch (Exception e){
            log.info(">>>收到检查job 处理数据异常",e);
        }

    }



    /**
     * 获取对应的公司和城市
     * 1.通过中继名称获得当前通道的所属城市
     * 2.通过当前的通道名，获得当前使用的ccid ，通过ccid 获得城市
     * @param redisData
     * @return
     */
    @Override
    public  String getRedisQueueCompanyAndCity(RedisData redisData){
        String city = "";
        String company = "";
        try {

            Map<String,String> map = redisTemplate.opsForHash().entries(redisData.getSn()+":"+redisData.getTrunkName());

            if(map!=null&&map.size()>0){
                city = map.get(RedisFields.CITY)==null?RedisKeys.DEFAULT_CITY:map.get(RedisFields.CITY);
                company = map.get(RedisFields.COMPANY)==null?RedisKeys.DEFAULT_COMPANY:map.get(RedisFields.COMPANY);
            }else{
                city = RedisKeys.DEFAULT_CITY;
                company = RedisKeys.DEFAULT_COMPANY;
            }

        }catch (Exception e){
            log.error(">>获取通道队列名称异常",e);
            city = RedisKeys.DEFAULT_CITY;
            company = RedisKeys.DEFAULT_COMPANY;
        }
        return company+":"+city;

    }




    /**
     * 激活时更新卡城市和ccid,公司,号码，sip用户
     * @param redisData
     */
    public void updateChannelSlotStateMap(RedisData redisData){
        try{
            List<GatewayCardSlotVo> list = gatewayCardSlotMapper.queryChannelTrunkInfoByTrunkName( redisData.getSn(),redisData.getChannel(),redisData.getSlotId());
            if(list!=null&&list.size()>0){
                for(GatewayCardSlotVo gatewayCardSlotVo:list) {
                    setChannelSlotStateMap(redisData,gatewayCardSlotVo);
                }
            }
        }catch (Exception e){
            log.error(">>激活卡是更新city失败");
        }

    }

    public void setChannelSlotStateMap(RedisData redisData,GatewayCardSlotVo gatewayCardSlotVo){
        Map<String,String> map = new HashMap<String,String>();
        if(StringTools.isNotempty(gatewayCardSlotVo.getCity())){
            map.put(RedisFields.CITY,gatewayCardSlotVo.getCity());
        }

        if(StringTools.isNotempty(gatewayCardSlotVo.getCcid())){
            map.put(RedisFields.CCID,gatewayCardSlotVo.getCcid());
        }

        if(StringTools.isNotempty(gatewayCardSlotVo.getBelongCompany())){
            map.put(RedisFields.COMPANY,gatewayCardSlotVo.getBelongCompany().getValue());
        }

        if(StringTools.isNotempty(gatewayCardSlotVo.getSipUser())){
            map.put(RedisFields.SIP_USER,gatewayCardSlotVo.getSipUser());
        }


        if(StringTools.isNotempty(gatewayCardSlotVo.getIp())){
            map.put(RedisFields.IP,gatewayCardSlotVo.getIp());
        }

        if(StringTools.isNotempty(gatewayCardSlotVo.getPhoneNum())){
            map.put(RedisFields.PHONE_NUM,gatewayCardSlotVo.getPhoneNum());
        }

        if(StringTools.isNotempty(gatewayCardSlotVo.getState())){
            map.put(RedisFields.EQUIPMENT_STATE,gatewayCardSlotVo.getState());
        }

        redisTemplate.opsForHash().putAll(RedisKeys.slotInfoKey(redisData.getSn(),redisData.getTrunkName()), map);
    }


}
